package com.datechange.demo.controller;

import cn.hutool.core.date.DateUtil;
import com.datechange.demo.entity.*;
import com.datechange.demo.service.CmsAttachmentService;
import com.datechange.demo.service.CmsChannelComparisonService;
import com.datechange.demo.service.CmsPublicContentService;
import com.datechange.demo.webservice.MyWebService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author XY
 * @version 1.0
 * @date 2020/12/14 11:49
 * @Description
 */
@RestController
@Api(tags = "数据迁移服务")
@RequestMapping(value="/transfer")
public class TestController {

    @Autowired
    CmsPublicContentService cmsPublicContentService;

    @Autowired
    CmsChannelComparisonService cmsChannelComparisonService;

    @Autowired
    CmsAttachmentService cmsAttachmentService;

    @Autowired
    MyWebService myWebService;

    @PostMapping("/addChannel")
    @ApiOperation(value = "添加频道", httpMethod = "POST")
    public void aa(){
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            //查询新老频道关联表
            List<CmsChannelComparison> cmsChannelComparisons = cmsChannelComparisonService.queryAllByLimit(0, 111);
            ArrayList<Channel> channels = new ArrayList<>();
            //判断需要进行新建的频道
            for (CmsChannelComparison cmsChannelComparison : cmsChannelComparisons) {
                if("需要新建".equals(cmsChannelComparison.getNewCode())&&"赵洪义".equals(cmsChannelComparison.getNewName())){
                    Channel channel = new Channel();
                    channel.setChannelname(cmsChannelComparison.getNewName());
                    channel.setChanneltitle(cmsChannelComparison.getNewName());
                    channel.setSupercode(cmsChannelComparison.getParentCode());
                    channel.setEchannelname("jdjh/zhy");
                    channel.setPubpath("sjmh");
                    channel.setNamemethod("/"+channel.getPubpath()+"/"+channel.getEchannelname()+"/{@year}/{@month}/{@UID}.htm");
                    channels.add(channel);
                }
            }
            for (Channel channel : channels) {
                StringBuilder url=new StringBuilder();
                url.append("?currSelectTabIndex="+channel.getCurrSelectTabIndex()).append("&channelType="+channel.getChannelType())
                    .append("&d_url="+channel.getD_url()).append("&chooseInfoStr="+channel.getChooseInfoStr())
                    .append("&chooseInfoIdStr="+channel.getChooseInfoIdStr()).append("&channelname="+channel.getChannelname())
                    .append("&domainurl="+channel.getDomainurl()).append("&ifgips="+channel.getIfgips()).append("&classid="+channel.getClassid())
                    .append("&echannelname="+channel.getEchannelname()).append("&namemethod="+channel.getNamemethod())
                    .append("&displayorder="+channel.getDisplayorder()).append("&channelmaxpage="+channel.getChannelmaxpage())
                    .append("&unitiveTopic="+channel.getUnitiveTopic()).append("&unitiveTopicFlag="+channel.getUnitiveTopicFlag())
                    .append("&templetid="+channel.getTempletid()).append("&templetidmore="+channel.getTempletidmore())
                    .append("&stempletid="+channel.getStempletid()).append("&mtempletid="+channel.getMtempletid())
                    .append("&mtempletidmore="+channel.getMtempletidmore()).append("&mstempletid="+channel.getMstempletid())
                    .append("&isshow="+channel.getIsshow()).append("&specialFlag="+channel.getSpecialFlag())
                    .append("&wfid="+channel.getWfid()).append("&description="+channel.getDescription())
                    .append("&superechannelname="+channel.getSuperechannelname()).append("&supercode="+channel.getSupercode())
                    .append("&listcount="+channel.getListcount()).append("&pubpath="+channel.getPubpath())
                    .append("&channeltitle="+channel.getChanneltitle()).append("&dosave="+channel.getDosave());
                String s = url.toString();
                String replace = s.replace("/", URLEncoder.encode("/", "UTF-8"))
                        .replace("{", URLEncoder.encode("{", "UTF-8"))
                        .replace("}", URLEncoder.encode("}", "UTF-8"))
                        .replace("@", URLEncoder.encode("@", "UTF-8"))
                        .replace(":", URLEncoder.encode(":", "UTF-8"))
                        .replace(channel.getChannelname(), URLEncoder.encode(channel.getChannelname(), "UTF-8"))
                        .replace(channel.getChanneltitle(), URLEncoder.encode(channel.getChanneltitle(), "UTF-8"));
                String uri="http://192.168.0.253:8080/cms/cmsadmin/channel/addchannel.jsp";
                uri+=replace;
                HttpPost httpPost = new HttpPost(uri);
//                HttpPost httpPost = new HttpPost("http://192.168.0.253:8080/cms/cmsadmin/channel/addchannel.jsp?currSelectTabIndex=1&channelType=HTML&d_url=http%3A%2F%2F&chooseInfoStr=&chooseInfoIdStr=&channelname=tes41&domainurl=&channeltitle=tes41&ifgips=0&classid=123456&echannelname=news&namemethod=%2Fsjmh%2Fzhuantithree%2Fnews%2F%7B%40year%7D%2F%7B%40month%7D%2F%7B%40UID%7D.htm&displayorder=0&channelmaxpage=20&unitiveTopic=&unitiveTopicFlag=1&templetid=1602792500762462&templetidmore=&stempletid=1606859054752025&mtempletid=1601824235533299&mtempletidmore=&mstempletid=1601824235533301&isshow=1&specialFlag=0&wfid=0&description=&superechannelname=%2Fsjmh%2Fzhuantithree&supercode=A0521&listcount=6&pubpath=sjmh&dosave=save");

                httpPost.setHeader("Cookie","JSESSIONID=376BC6CAEDA45145E387B2E313E12D7C");
                String responseBody = httpClient.execute(httpPost, httpResponse -> {
                    int status = httpResponse.getStatusLine().getStatusCode();
                    if (status < 200 || status >= 300) {
                        // ... handle unsuccessful request
                        System.out.println("error");
                    }
                    HttpEntity entity = httpResponse.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                });
                // ... do something with response
                System.out.println("success");
            }
        } catch (IOException e) {
            // ... handle IO exception
            e.printStackTrace();
        }
    }

    @PostMapping("/test")
    @ApiOperation(value = "同步", httpMethod = "POST")
    @Transactional(rollbackFor = Exception.class)
    public void test(@RequestParam(value = "topOrgCode", required = true) String topOrgCode, String ccId){
        try {
            //查老数据
            List<CmsPublicContent> list = cmsPublicContentService.list(topOrgCode,ccId);
            for (CmsPublicContent item : list) {
                String id = StringUtils.hasText(ccId)?ccId:item.getCcId();
                //根据老频道id和顶级组织编码查询到新老频道对应关系，一般只查询到一条数据，特殊情况下会有多条
                List<CmsChannelComparison> cmsChannelComparisons = cmsChannelComparisonService.selectByCcId(id,item.getCpcUnitCode());
                System.exit(0);
                CmsChannelComparison c1=null;
                if(cmsChannelComparisons!=null&&cmsChannelComparisons.size()>0){
                    for (CmsChannelComparison cmsChannelComparison : cmsChannelComparisons) {
                        //主要领导类，老数据只有主要领导频道，新的要具体到某个人
                        if(cmsChannelComparison.getType().equals("3")){
                            //这里用老数据的内容标题去查与之对应的新频道，如老数据内容的标题为孙晓莹xxxxxxxx，那新的频道就是孙晓莹
                            String cpcTitle = item.getCpcTitle();
                            //如果老数据内容标题里含有新数据的频道名就根据该频道名查询
                            if(cpcTitle.contains(cmsChannelComparison.getNewName())){
                                CmsChannelComparison res = cmsChannelComparisonService.selectByTitle(cmsChannelComparison.getNewName());
                                c1=res;
                            }
                        //人员组成，工作职责类
                        }else if (cmsChannelComparison.getType().equals("2")){
                            String cpcTitle = item.getCpcTitle();
                            //newCode一般是 A05270701(人员组成),A05270702(工作职责) 的字符串，特殊情况下只有一个
                            String newCode = cmsChannelComparison.getNewCode();
                            //将code转换为数组
                            String[] split = newCode.split(",");
                            //如果老数据内容中包含人员组成，则插入到新库中的频道就是人员组成（A05270701）
                            if(split.length>1&&cpcTitle.contains("人员组成")){
                                cmsChannelComparison.setNewCode(split[0]);
                                c1=cmsChannelComparison;
                            }else if(split.length>1&&cpcTitle.contains("工作职责")){
                                //工作职责
                                cmsChannelComparison.setNewCode(split[1]);
                                c1=cmsChannelComparison;
                            }else{
                                //特殊情况，split中只有一条数据
                                c1=cmsChannelComparison;
                            }
                        }else{
                            //其他类
                            c1=cmsChannelComparison;
                        }
                    }
                    //查询老数据所带的附件
                    List<CmsAttachment> attachs = new ArrayList<>();
                    CmsAttachment cmsAttachment = new CmsAttachment();
                    cmsAttachment.setCaFileName("测试");
                    cmsAttachment.setCaLogicPath("/t/t");
                    cmsAttachment.setCaBId(item.getCpcId());
                    cmsAttachment.setCaiId("123");
                    cmsAttachment.setCaId(UUID.randomUUID().toString().replace("-",""));
                    attachs.add(cmsAttachment);
                    if(attachs!=null&&attachs.size()>0){
                        //先将附件同步到附件临时表，后续回写新路径的时候需要用到
                        for (CmsAttachment attachment : attachs) {
                            cmsAttachmentService.insert(attachment);
                        }
                        //同步附件，需要传入频道编码，并回写同步后返回的新路径到附件临时表
                        myWebService.putFileToChannelAndUpdate(attachs,c1.getNewCode());
                    }
                    ContentObject contentObject = new ContentObject();
                    contentObject.setTochannel(c1.getNewCode());
                    contentObject.setTopic(item.getCpcTitle());
                    contentObject.setSecondtopic(item.getCpcSubTitle());
                    contentObject.setAuthorname(item.getCpcAuthor());
                    contentObject.setDescription(item.getCpcKeys());
                    contentObject.setOrigin(item.getCpcSource());
                    contentObject.setDeptcode(item.getCpcUnitCode());
                    contentObject.setFilltime(DateUtil.formatDate(item.getCpcDraftTime()));
                    contentObject.setContenttype("HTML");
                    String cpcContent = item.getCpcContent();
                    String substring="";
                    String img = "";
                    Pattern p_image;
                    Matcher m_image;
                    List<String> pics = new ArrayList<String>();
                    String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
                    p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
                    //找到所有的img标签中的src中的地址，并存入集合
                    m_image = p_image.matcher(cpcContent);
                    while (m_image.find()) {
                        img = img + "," + m_image.group();
                        // Matcher m =
                        // Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); //匹配src
                        Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
                        while (m.find()) {
                            pics.add(m.group(1));
                        }
                    }
                    //遍历集合
                    for (String pic : pics) {
                        System.out.println(pic);
                        //字符串切割
                        String[] split = pic.split("imgName=/");
                        //将'imgName=/'之后的内容解码
                        String decode = URLDecoder.decode(split[1],"UTF-8");
                        //替换地址和乱码的字符串
                        cpcContent=cpcContent.replace("http://10.9.3.206:10039/cms/CmsPc/getUploadImg?imgName=/","http://test.com")
                        .replace(split[1],decode);

                    }
                    //内容只需要<body>标签内的东西
                    if(cpcContent.contains("<body>")&&cpcContent.contains("</body>")){
                        substring = cpcContent.substring(cpcContent.indexOf("<body>") + 6, cpcContent.indexOf("</body>"));
                    }else{
                        substring = cpcContent;
                    }
                    //将新的附件路径添加到内容正文中,这里用的是同步附件之后回写的新路径
                    List<CmsAttachment> res = cmsAttachmentService.findBycaBId(item.getCpcId());
                    if(res!=null&&res.size()>0){
                        for (CmsAttachment re : res) {
                            substring+="<a href="+re.getNewFilePath()+">"+re.getNewFileName()+"</a>";
                        }
                    }
                    contentObject.setContent(substring);
                    contentObject.setInfostate(item.getCpcStatus());
                    contentObject.setInfostate("P");
                    contentObject.setWebservicecode("cmsok");
                    contentObject.setUserid(item.getCpcCreateUserid());
                    //同步内容
                    myWebService.doinfo(contentObject);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
